package com.future.mayi.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.statusbarlibrary.StatusBarUtils;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.ShareGoodsDialog;
import com.future.mayi.dialog.UpdateDialog;
import com.future.mayi.fragment.CartFragment;
import com.future.mayi.fragment.IndexFragment;
import com.future.mayi.fragment.MyFragment;
import com.future.mayi.fragment.SortFragment;
import com.future.mayi.jpush.JPushManager;
import com.future.mayi.model.VersionModel;
import com.future.mayi.response.MyIndexResponse;
import com.future.mayi.response.VersionResponse;
import com.future.mayi.utils.ClickUtils;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.SharedPreferencesUtils;
import com.future.mayi.widget.BottomTabBar;
import com.pgyersdk.update.DownloadFileListener;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements BottomTabBar.OnItemClickListener {

    public static boolean statusBar = false;
    public static int statusBarHeight;
    @BindView(R.id.fl_main)
    FrameLayout flMain;
    @BindView(R.id.bottom_tab_bar)
    BottomTabBar bottomTabBar;

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private IndexFragment indexFragment;
    private SortFragment sortFragment;
    private CartFragment cartFragment;
    private MyFragment myFragment;

    private String userId;
    private int onItem = 0;


    @Override
    protected void initLayout() {
        if (StatusBarUtils.setStatusBarTranslucent(getWindow(), true)) {
            statusBar = true;
            statusBarHeight = CommonUtils.getStatusBarHeight(this);
            StatusBarUtils.setStatusBarColor(getWindow(), Color.TRANSPARENT, false);
        }
        setContentView(R.layout.activity_main);

//        if (ApiCst.DEBUG) {
//            findTextView(R.id.tv_test_code).setVisibility(View.VISIBLE);
//            findTextView(R.id.tv_test_code).setText(String.valueOf(CommonUtils.getAppVersion(mContext)));
//            findViewById(R.id.ll_test_update).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent();
//                    intent.setAction("android.intent.action.VIEW");
//                    Uri content_url = Uri.parse("https://www.pgyer.com/jr2E");
//                    intent.setData(content_url);
//                    mContext.startActivity(intent);
//                }
//            });
//        }

    }

    @Override
    protected void initView() {
        initFragment();
    }

    @Override
    protected void initDates() {
        userId = App.getUid();
//        getAppVersion();
        getCityData();
    }

    @Override
    protected void initListener() {
        bottomTabBar.setOnItemClickListener(this);
        if (getIntent() != null) {
            //处理通知点击产生的事件
            String extraMsg = getIntent().getStringExtra(JPushManager.EXTRA_EXTRA);
            if (!TextUtils.isEmpty(extraMsg)) {
                startActivity(com.future.mayi.jpush.Navigator.getNotificationListIntent(this, extraMsg));
            }
        }
    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        indexFragment = new IndexFragment();
        sortFragment = new SortFragment();
        cartFragment = new CartFragment();
        myFragment = new MyFragment();
        fragmentTransaction.add(R.id.fl_main, indexFragment);
        fragmentTransaction.add(R.id.fl_main, sortFragment);
        fragmentTransaction.add(R.id.fl_main, cartFragment);
        fragmentTransaction.add(R.id.fl_main, myFragment);

        fragmentTransaction.hide(sortFragment);
        fragmentTransaction.hide(cartFragment);
        fragmentTransaction.hide(myFragment);
        fragmentTransaction.commit();
    }

    @SuppressLint("RestrictedApi")
    @Override
    public void onItem(int onItem) {
        if (this.onItem == onItem)
            return;

        if ((onItem == 2 || onItem == 3) && ClickUtils.isNoLogin(mContext, true)) {
            bottomTabBar.setOnItem(this.onItem);
            return;
        }

        this.onItem = onItem;


        if (onItem == 0 && indexFragment != null) {
            StatusBarUtils.setStatusBarColor(getWindow(), getResources().getColor(R.color.main_color), false);
            indexFragment.showFragment();
        } else if (onItem == 1 && sortFragment != null) {
            StatusBarUtils.setStatusBarColor(getWindow(), getResources().getColor(R.color.white), false);
            sortFragment.showFragment();
        } else if (onItem == 2 && cartFragment != null) {
            StatusBarUtils.setStatusBarColor(getWindow(), getResources().getColor(R.color.white), false);
            cartFragment.showFragment();
        } else if (onItem == 3 && myFragment != null) {
            StatusBarUtils.setStatusBarColor(getWindow(), getResources().getColor(R.color.main_color), false);
            myFragment.showFragment();
        }

        fragmentTransaction = fragmentManager.beginTransaction();
        for (Fragment fragment : fragmentManager.getFragments()) {
            if (onItem == fragmentManager.getFragments().indexOf(fragment)) {
                fragmentTransaction.show(fragment);
            } else {
                fragmentTransaction.hide(fragment);
            }
        }
        fragmentTransaction.commit();
    }


    @Override
    public void onDoubleClick(int position) {

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && intent.getBooleanExtra("intentToIndexFragment", false)) {
            bottomTabBar.setOnItem(0);
            return;
        }


        if (TextUtils.equals(App.getUid(), userId))
            return;
        userId = App.getUid();
        indexFragment.refresh();
        sortFragment.refresh();
        cartFragment.refresh();
        myFragment.refresh();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (ClickUtils.isNoLogin(this, false) && (onItem == 2 || onItem == 3)) {
            bottomTabBar.setOnItem(0);
        }

//        if (ApiCst.DEBUG) {
//            getAppTestVersion();
//        }

        if (onItem == 0 && indexFragment != null)
            indexFragment.showFragment();
        if (onItem == 1 && sortFragment != null)
            sortFragment.showFragment();
        if (onItem == 2 && cartFragment != null)
            cartFragment.showFragment();
        if (onItem == 3 && myFragment != null)
            myFragment.showFragment();

        if (App.isLogin()) {
            getUserInfo();
        }
    }


    private UpdateDialog updateDialog;

    private void getAppVersion() {
        new HttpRequest<VersionResponse>()
                .with(this)
                .setApiCode(ApiCst.getAppVersion)
                .addParam("type", 1)
                .setListener(new HttpRequest.OnNetworkListener<VersionResponse>() {
                    @Override
                    public void onSuccess(VersionResponse baseResponse) {
                        VersionModel model = baseResponse.model;
                        if (model == null) return;
                        String oldVersion = CommonUtils.getAppVersion(mContext);
                        if (!CommonUtils.needUpdate(oldVersion, model.getVersion()))
                            return;
                        if (updateDialog == null) {
                            updateDialog = new UpdateDialog(MainActivity.this);
                        }
                        updateDialog.show(model);
                    }

                    @Override
                    public void onFail(String message, VersionResponse response) {
                        dissmissLoadingDialog();
                        HCUtils.loadFail(mContext, message);
                    }
                }).start(new VersionResponse());
    }


    private void getAppTestVersion() {
        new PgyUpdateManager.Builder()
                .setForced(true)
                .setUserCanRetry(false)
                .setDeleteHistroyApk(false)
                .setUpdateManagerListener(new UpdateManagerListener() {
                    @Override
                    public void onNoUpdateAvailable() {
                        findViewById(R.id.ll_test_update).setVisibility(View.GONE);
                    }

                    @Override
                    public void onUpdateAvailable(AppBean appBean) {
                        findViewById(R.id.ll_test_update).setVisibility(View.VISIBLE);
                        toast("发现新版本，自动下载中");
                        PgyUpdateManager.downLoadApk(appBean.getDownloadURL());
                    }

                    @Override
                    public void checkUpdateFailed(Exception e) {
                    }
                })
                .setDownloadFileListener(new DownloadFileListener() {
                    @Override
                    public void downloadFailed() {
                        toast("新版本自动下载失败，请到蒲公英更新");
                    }

                    @Override
                    public void downloadSuccessful(Uri uri) {
                        toast("新版本自动下载成功，请安装更新");
                        PgyUpdateManager.installApk(uri);
                    }

                    @Override
                    public void onProgressUpdate(final Integer... integers) {
                        ((ProgressBar) findViewById(R.id.pb_test)).setProgress(integers[0]);
                    }
                })
                .register();
    }


    private void getCityData() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.getCityCommon)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        if (!TextUtils.isEmpty(response.content))
                            SharedPreferencesUtils.set(mContext, SharedPreferencesUtils.SpEnum.City, response.content);
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                    }
                })
                .start(new DefaultResponse());
    }


    @SuppressWarnings("unchecked")
    public void getUserInfo() {
        if (!App.isLogin()) return;
        new HttpRequest<MyIndexResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.myIndex)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<MyIndexResponse>() {

                    @Override
                    public void onSuccess(MyIndexResponse response) {
                        if (indexFragment == null || myFragment == null) return;
                        if (response.userInfoModel == null) return;
                        if (response.levelupModel == null) return;
                        if (response.orderNumModel == null) return;
                        if (response.saleModel == null) return;
                        indexFragment.refreshMsgCount(response.msgCount);
                        myFragment.setUser(response.userInfoModel, response.levelupModel);
                        myFragment.setOrder(response.orderNumModel);
                        myFragment.refreshMsgCount(response.msgCount);
                        myFragment.refreshMoney(response.saleModel);
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.LoginNickName, response.userInfoModel.getNickname());
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.LoginHeadImg, response.userInfoModel.getAvatar());
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.WalletBalance, response.userInfoModel.getMoney());
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.LoginUserLevel, response.userInfoModel.getLevel());
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.InviteCode, TextUtils.isEmpty(response.userInfoModel.getInvite_code()) ? "" : response.userInfoModel.getInvite_code());
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.Referee, TextUtils.isEmpty(response.userInfoModel.getReferee()) ? "" : response.userInfoModel.getReferee());
                    }

                    @Override
                    public void onFail(String message, MyIndexResponse response) {
                    }
                }).start(new MyIndexResponse());
    }
}
